<template>
  <div class="item-btn item-btn-active" @click="payHandler">付款</div>
</template>

<script>
// api
import { pay } from '@/api/miva'
// vant
import { Toast } from 'vant'
export default {
  props: {
    orderInfo: {
      type: Object,
      default() {
        return {}
      }
    }
  },
  methods: {
    async payHandler() {
      console.log('支付按钮-log')
      const data = {
        orders_num: this.orderInfo.orders_num,
        pay_money: this.orderInfo.orders_total
      }
      console.log(data)
      const res_pay = await pay(data)
      console.log(res_pay)
      this.isBridgeReady(res_pay.data.data)
    },
    // 支付api注册方法
    isBridgeReady(res_pay) {
      console.log(res_pay)
      const { onBridgeReady } = this
      if (typeof WeixinJSBridge === 'undefined') {
        if (document.addEventListener) {
          document.addEventListener(
            'WeixinJSBridgeReady',
            onBridgeReady,
            false
          )
          console.log(951)
        } else if (document.attachEvent) {
          document.attachEvent('WeixinJSBridgeReady', onBridgeReady)
          document.attachEvent('onWeixinJSBridgeReady', onBridgeReady)
          console.log(789)
        }
        console.log(456)
      } else {
        console.log(123)
        onBridgeReady(res_pay)
      }
    },
    // 支付处理器
    onBridgeReady(res_pay) {
      // alert(JSON.stringify(res_pay))
      console.log('支付处理器')
      // const { appId, nonceStr, sign, signType, timeStamp } = res_pay
      const params = {
        appId: res_pay.appId, // 公众号名称，由商户传入
        timeStamp: res_pay.timeStamp.toString(), // 时间戳，自1970年以来的秒数
        nonceStr: res_pay.nonceStr, // 随机串
        package: res_pay.package,
        signType: res_pay.signType, // 微信签名方式：
        paySign: res_pay.sign // 微信签名
      }
      console.log(params)
      // alert(JSON.stringify(params))
      WeixinJSBridge.invoke('getBrandWCPayRequest', params, res => {
        // alert(JSON.stringify(res))
        if (res.err_msg === 'get_brand_wcpay_request:ok') {
          Toast({ type: 'danger', message: '支付成功' })
          this.routerLink(`buySucc`)
        } else {
          Toast({ type: 'danger', message: '支付未成功' })
        }
      })
    },
    routerLink(name) {
      this.$router.replace({ name })
    }
  }
}
</script>
